<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.username" placeholder="用户名" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter"/>
      <el-input v-model="listQuery.operation" placeholder="用户操作" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter"/>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        高级查询
      </el-button>


    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80"
                       >
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户名" width="130px">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户操作" width="130px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.operation }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请求方法" width="170px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.method }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请求参数" width="280px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.params}}</span>
        </template>
      </el-table-column>
      <el-table-column label="执行时长" class-name="status-col" width="120">
        <template slot-scope="{row}">
          <span>{{ row.time}}</span>
        </template>
      </el-table-column>
      <el-table-column label="IP地址" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.ip }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createDate }}</span>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"/>



  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<script>
  import {fetchList, fetchPv, createArticle, updateArticle} from '@/api/article'
  import waves from '@/directive/waves' // waves directive
  import {parseTime} from '@/utils'
  import Pagination from '@/components/Pagination'
  import request from "@/utils/request"; // secondary package based on el-pagination

  const calendarTypeOptions = [
    {key: 'CN', display_name: 'China'},
    {key: 'US', display_name: 'USA'},
    {key: 'JP', display_name: 'Japan'},
    {key: 'EU', display_name: 'Eurozone'}
  ]

  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'ComplexTable',
    components: {Pagination},
    directives: {waves},
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        imageUrl: '',
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          username: undefined,
          operation: undefined
        },
        importanceOptions: [1, 2, 3],
        calendarTypeOptions,
        sortOptions: [{label: 'ID Ascending', key: '+id'}, {label: 'ID Descending', key: '-id'}],
        statusOptions: [
          {id: 0, value: "禁用"}, {id: 1, value: "正常"}
        ],
        showReviewer: false,
        temp: {
          id: undefined,
          name: '',
          timestamp: new Date(),
          type: '',
          status: 0,
          images: ''
        },
        dialogStatus: '',
        textMap: {
          update: '编辑社团',
          create: '新建社团'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          type: [{required: true, message: 'type is required', trigger: 'change'}],
          timestamp: [{type: 'date', required: true, message: 'timestamp is required', trigger: 'change'}],
          title: [{required: true, message: 'title is required', trigger: 'blur'}]
        },
        downloadLoading: false
      }
    },
    created() {
        this.getList(),
        this.getTypeList(), //请求类型列表
        this.getUserList()
    },
    methods: {
      handleAvatarSuccess(res, file) {
        // this.imageUrl = URL.createObjectURL(file.raw);
        this.imageUrl = "http://localhost:9999/" + res.msg;
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 png 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },

      //创建获取用户列表的方法
      getUserList() {
        request(
          {
            url: 'userinfo/queryUserInfoList',
            method: 'get'
          }).then(res => {
          if (res.code == 20000) {
            this.userList = res.data;
          }
        })
      },

      //获取类型列表
      getTypeList() {
        request(
          {
            url: 'typeInfo/queryTypeList',
            method: 'get'
          }).then(res => {
          if (res.code == 20000) {
            this.typeList = res.data;
          }
        })
      },
      getList() {
        /**
         * 1、发送请求 返回结果集合
         * 2、根据结果集合渲染页面
         * 3、把加载框取消为false
         */
        this.listLoading = true;//没有信息之前显示加载内容
        console.log(this.listQuery)
        request(
          {
            url: 'http://localhost:9999/log/queryLogList',
            method: 'get',
            params: this.listQuery
          }).then(res => {
          if (res.code == 20000) {
            console.log(res);
            this.list = res.data;
            this.total = res.total;
            this.listLoading = false;
          }
        }).catch(err => {

        })

      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作Success',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const {prop, order} = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.imageUrl = '',
          this.temp = {
            id: undefined,
            importance: 1,
            remark: '',
            timestamp: new Date(),
            title: '',
            status: '',
            type: '',
            imageUrl: ''
          }
      },
      //新增表单
      handleCreate() {

        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      //新增表单提交
      createData() {

        /**
         * 1、获取form单中的数据信息
         * 2、向后端服务器发送请求  完成请求操作
         * 3、服务器端处理完成后 返回状态码
         * 4、前端如果接收 添加成功
         *    进行table刷新 弹出框关闭
         */
        this.temp.images = this.imageUrl;//图片变量的赋值操作
        this.userList = this.getUserList();
        debugger
        console.log(this.temp);
        request.post('http://localhost:9999/team/addInfo', this.temp).then(res => {
          if (res.code == 20000) {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '新建社团成功',
              type: 'success',
              duration: 2000
            })
            this.getList();//刷新table组件
          }
        })

      },
      //删除操作
      handleDelete(row, index) {
        /**
         * 1、获取要删除记录的id 主键
         * 2、发送请求给后端服务器
         * 3、前后端根据后端服务器返回结果判断是否成功
         * 4、成功的话 重新加载table 展示最新内容
         */
        request('http://localhost:9999/team/deleteByID?id=' + row.id).then(res => {
          if (res.code == 20000) {
            this.$notify({
              title: 'Success',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList();
          }
        })

      },
      handleFetchPv(pv) {
        fetchPv(pv).then(response => {
          this.pvData = response.data.pvData
          this.dialogPvVisible = true
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      getSortClass: function (key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
</script>
